package com.kaaction.modules.mer.api;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.web.BaseController;
import com.kaaction.modules.eb.entity.Customer;
import com.kaaction.modules.mer.entity.Address;
import com.kaaction.modules.mer.entity.MerClassify;
import com.kaaction.modules.mer.entity.MerOrder;
import com.kaaction.modules.mer.entity.OrderSku;
import com.kaaction.modules.mer.entity.Sku;
import com.kaaction.modules.mer.entity.Spu;
import com.kaaction.modules.mer.service.AddressService;
import com.kaaction.modules.mer.service.MerOrderService;
import com.kaaction.modules.mer.service.OrderSkuService;
import com.kaaction.modules.mer.service.SkuService;
import com.kaaction.modules.weixinpay.WeixinMiniProgramApi;

@Controller
@RequestMapping(value = "/api/v1/order")
public class MerOrderApiController extends BaseController {

	@Autowired
	private OrderSkuService orderSkuService;

	@Autowired
	private SkuService skuService;

	@Autowired
	private MerOrderService merOrderService;
	
	@Autowired
	AddressService addressService;

	private final String IN_ORDER = "30";
	
	
	/**
	 * 获取某个人的订单列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/get")
	public void get(HttpServletRequest request, HttpServletResponse response) {
		logger.info("获取某人的订单列表");
		String openId = request.getParameter("openId");
		String orderId = request.getParameter("id");
		
		MerOrder merOrder = merOrderService.get(orderId);
		if(merOrder != null) {
			MerOrder mOrder = new MerOrder();
			mOrder.setId(merOrder.getId());
			
			OrderSku orderSku = new OrderSku();
			orderSku.setOrder(mOrder);
			
			List<OrderSku> orderSkuList = orderSkuService.findList(orderSku);
			if(orderSkuList != null){
				merOrder.setOrderSkuList(orderSkuList);
				super.writeAjaxResponse(response, merOrder);
			} else {
				super.writeFailResponse(response, "", "没有找到订单明细");
			}
		} else {
			super.writeFailResponse(response, "", "没有找到订单");
		}
		
	}
	
	/**
	 * 获取某个人的订单列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/update")
	public void update(HttpServletRequest request, HttpServletResponse response) {
		logger.info("获取某人的订单列表");
		String openId = request.getParameter("openId");
		String orderId = request.getParameter("id");
		String status = request.getParameter("status");
		
		MerOrder merOrder = merOrderService.get(orderId);
		if(merOrder != null) {
			merOrder.setStatus(status);
			if("60".equals(status))merOrder.setExpressStartDate(new Date());
			merOrderService.save(merOrder);
			super.writeAjaxResponse(response, merOrder);
		} else {
			super.writeFailResponse(response, "", "unkown");
		}
		
	}
	/**
	 * 获取某个人的订单列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/list")
	public void list(HttpServletRequest request, HttpServletResponse response) {
		logger.info("获取某人的订单列表");
		String openId = request.getParameter("openId");
		String isPhoto = request.getParameter("isPhoto");
		logger.info("openId = " + openId);
		MerOrder order = new MerOrder();
		Customer customer = new Customer();
		customer.setThirdpartyId(openId);
		order.setCustomer(customer);
		order.setIsPhoto(isPhoto);
		//TODO 不做分页了
		//Page<MerOrder> orderList = merOrderService.findPage(new Page<MerOrder>(request, response), order);
		List<MerOrder> orderList = merOrderService.findList(order);
		for(int i = 0 ; i < orderList.size(); i++ ){
			MerOrder merOrder = orderList.get(i);
			MerOrder mOrder = new MerOrder();
			mOrder.setId(merOrder.getId());
			OrderSku orderSku = new OrderSku();
			orderSku.setOrder(mOrder);
			List<OrderSku> skuList = orderSkuService.findList(orderSku);
			if(skuList != null)merOrder.setOrderSkuList(skuList);
		}
		
		super.writeAjaxResponse(response, orderList);
	}

	/**
	 * 删除一个订单
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/delete")
	public void delete(HttpServletRequest request, HttpServletResponse response) {
		logger.info("删除一条订单");
		String id = request.getParameter("id");
		logger.info("id=" + id);

		MerOrder order = new MerOrder();
		order.setId(id);
		merOrderService.delete(order);
		super.writeAjaxResponse(response, "");
	}

	/**
	 * 购买摄影类产品
	 * 
	 * @param request
	 * @param response
	 * @throws DocumentException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/addOrderForPhoto")
	public void addOrderForPhoto(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, DocumentException {
		String openId = request.getParameter("openId");
		String spuId = request.getParameter("spuId");

		Sku sku = skuService.findSkuBySpuId(spuId);
		if (sku != null) {
			logger.info("找到对应的sku，id=" + sku.getId());
				int skuNum = 1;

				Customer customer = new Customer();
				customer.setThirdpartyChannel("wechat");
				customer.setThirdpartyId(openId);

				MerOrder mOrder = new MerOrder();
				mOrder.setCustomer(customer);
				mOrder.setStatus(IN_ORDER);
				mOrder.setExpressStartDate(new Date());
//				mOrder.setPayDate(new Date());
				mOrder.setIsPhoto("1");
				mOrder.setShowCode(StringUtils.getUniqueString());
				
				String addressId = request.getParameter("addressId");
				logger.info("addressId = " + addressId);
				if(!StringUtils.isBlank(addressId)){
					Address address = addressService.get(addressId);
					logger.info("addressId == null? " + (address == null));
					if(address != null){
						logger.info("name:"+address.getName());
						logger.info("mobile:"+address.getMobile());
						logger.info("province:"+address.getProvince());
						logger.info("city:"+address.getCity());
						logger.info("county:"+address.getCounty());
						logger.info("address:"+address.getAddress());
						
						if(address.getName() != null)mOrder.setRecipientName(address.getName());
						if(address.getMobile() != null)mOrder.setRecipientMobile(address.getMobile());
						if(address.getProvince() != null)mOrder.setRecipientProvince(address.getProvince());;
						if(address.getCity() != null)mOrder.setRecipientCity(address.getCity());
						if(address.getCounty() != null)mOrder.setRecipientCounty(address.getCounty());
						if(address.getAddress() != null)mOrder.setRecipientAddress(address.getAddress());
					}
				}
				
				String remarks = request.getParameter("remarks");
				mOrder.setRemarks(remarks);

				merOrderService.save(mOrder);
				logger.info("新订单的编号: " + mOrder.getId());

				OrderSku orderSku = new OrderSku();
				orderSku.setOrder(mOrder);
				orderSku.setCustomer(customer);
				orderSku.setSku(sku);
				orderSku.setSkuNum(skuNum);
				orderSku.setType(IN_ORDER);
				logger.info("准备往购物车增加一条记录:" + JSON.toJSONString(orderSku));
				orderSkuService.save(orderSku);
				
				double topayFee = skuNum * sku.getPrice();
				mOrder.setRawPrice(topayFee);
				mOrder.setCurrentPrice(topayFee);
				logger.info("3.更新订单的价格为：" + topayFee);
				merOrderService.save(mOrder);
				
				
				commonResponse(request,response,openId,mOrder.getId(),"结呗商品",sku.getPrice() * skuNum);
			logger.info("添加到购物车成功...");
		} else {
			logger.info("没有对应的商品");
			super.writeFailResponse(response, "", "没有对应的商品");
		}

	
		
	}
	
	/**
	 * 直接购买
	 * 
	 * @param request
	 * @param response
	 * @throws DocumentException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/addOrderDirect")
	public void add(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, DocumentException {
		logger.info("直接购买");
		String openId = request.getParameter("openId");
		String spuId = request.getParameter("spuId");
		String spuNumStr = request.getParameter("productNum");
		String spuParams = request.getParameter("productSaleAttrsSplitWithComma");
		
		String selectedColorId = "";
		String selectedSizeId = "";

		logger.info("============获取请求中的参数start=========");
		logger.info("openId = " + openId);
		logger.info("productId = " + spuId);
		logger.info("productNum = " + spuNumStr);
		logger.info("productParam = " + spuParams);
		logger.info("============获取请求中的参数end=========");

		// TODO 放到service层，事务中
		if (!StringUtils.isBlank(spuParams) && spuParams.indexOf(",") > -1) {
			String[] params = spuParams.split(",");
			selectedColorId = params[0];
			selectedSizeId = params[1];
			Sku sku = skuService.findSku(spuId, selectedColorId, selectedSizeId);
			if (sku != null) {
				logger.info("找到对应的sku，id=" + sku.getId());
				int skuNum = 0;
				if (!StringUtils.isBlank(spuNumStr)) {
					skuNum = Integer.parseInt(spuNumStr);

					Customer customer = new Customer();
					customer.setThirdpartyChannel("wechat");
					customer.setThirdpartyId(openId);

					MerOrder mOrder = new MerOrder();
					mOrder.setCustomer(customer);
					mOrder.setStatus(IN_ORDER);
					mOrder.setExpressStartDate(new Date());
					mOrder.setIsPhoto("0");
					mOrder.setShowCode(StringUtils.getUniqueString());
					
					String addressId = request.getParameter("addressId");
					logger.info("addressId = " + addressId);
					if(!StringUtils.isBlank(addressId)){
						Address address = addressService.get(addressId);
						logger.info("addressId == null? " + (address == null));
						if(address != null){
							logger.info("name:"+address.getName());
							logger.info("mobile:"+address.getMobile());
							logger.info("province:"+address.getProvince());
							logger.info("city:"+address.getCity());
							logger.info("county:"+address.getCounty());
							logger.info("address:"+address.getAddress());
							if(address.getName() != null)mOrder.setRecipientName(address.getName());
							if(address.getMobile() != null)mOrder.setRecipientMobile(address.getMobile());
							if(address.getProvince() != null)mOrder.setRecipientProvince(address.getProvince());;
							if(address.getCity() != null)mOrder.setRecipientCity(address.getCity());
							if(address.getCounty() != null)mOrder.setRecipientCounty(address.getCounty());
							if(address.getAddress() != null)mOrder.setRecipientAddress(address.getAddress());
						}
					}
					String remarks = request.getParameter("remarks");
					mOrder.setRemarks(remarks);
					
					merOrderService.save(mOrder);
					logger.info("新订单的编号: " + mOrder.getId());

					OrderSku orderSku = new OrderSku();
					orderSku.setOrder(mOrder);
					orderSku.setCustomer(customer);
					orderSku.setSku(sku);
					orderSku.setSkuNum(skuNum);
					orderSku.setType(IN_ORDER);
					logger.info("准备往购物车增加一条记录:" + JSON.toJSONString(orderSku));
					orderSkuService.save(orderSku);
					
					double topayFee = skuNum * sku.getPrice();
					mOrder.setRawPrice(topayFee);
					mOrder.setCurrentPrice(topayFee);
					logger.info("3.更新订单的价格为：" + topayFee);
					merOrderService.save(mOrder);
					
					
					commonResponse(request,response,openId,mOrder.getId(),"结呗商品",sku.getPrice() * skuNum);
				}
				logger.info("添加到购物车成功...");
			} else {
				logger.info("没有对应的商品");
				super.writeFailResponse(response, "", "没有对应的商品");
			}

		} else {
			logger.info("productParam参数不完整");
			super.writeFailResponse(response, "", "productSaleAttrSplitWithComma参数不完整，请提供颜色id和尺寸id，用逗号隔开");
		}
	}

	/**
	 * 从购物车购买
	 * 
	 * @param request
	 * @param response
	 * @throws DocumentException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/addOrderFromCart")
	public void addOrderFromCart(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, DocumentException {
		logger.info("从购物车购买");
		String openId = request.getParameter("openId");
		String skuIds = request.getParameter("skuIds");
		String skuNums = request.getParameter("productNums");
		
		logger.info("============获取请求中的参数start=========");
		logger.info("openId = " + openId);
		logger.info("productIds = " + skuIds);
		logger.info("productNums = " + skuNums);
		logger.info("============获取请求中的参数end=========");

		Customer customer = new Customer();
		customer.setThirdpartyChannel("wechat");
		customer.setThirdpartyId(openId);

		// 1.生成1条order记录，记录当前金额
		MerOrder mOrder = new MerOrder();
		mOrder.setCustomer(customer);
		mOrder.setStatus(IN_ORDER);
		mOrder.setExpressStartDate(new Date());
		mOrder.setIsPhoto("0");
		mOrder.setShowCode(StringUtils.getUniqueString());
		
		String addressId = request.getParameter("addressId");
		logger.info("addressId = " + addressId);
		if(!StringUtils.isBlank(addressId)){
			Address address = addressService.get(addressId);
			logger.info("addressId == null? " + (address == null));
			if(address != null){
				logger.info("name:"+address.getName());
				logger.info("mobile:"+address.getMobile());
				logger.info("province:"+address.getProvince());
				logger.info("city:"+address.getCity());
				logger.info("county:"+address.getCounty());
				logger.info("address:"+address.getAddress());
				if(address.getName() != null)mOrder.setRecipientName(address.getName());
				if(address.getMobile() != null)mOrder.setRecipientMobile(address.getMobile());
				if(address.getProvince() != null)mOrder.setRecipientProvince(address.getProvince());;
				if(address.getCity() != null)mOrder.setRecipientCity(address.getCity());
				if(address.getCounty() != null)mOrder.setRecipientCounty(address.getCounty());
				if(address.getAddress() != null)mOrder.setRecipientAddress(address.getAddress());
			}
		}
		String remarks = request.getParameter("remarks");
		mOrder.setRemarks(remarks);
		
		merOrderService.save(mOrder);
		logger.info("1.新增了一条订单");

		// 2.更新ordersku表中相关状态
		double topayFee = 0.0;
		String[] skuArr = skuIds.split(",");
		String[] skuNumArr = skuNums.split(",");
		// 2.1 遍历，根据openid和skuId找到每条记录，更新orderid、num和status
		for (int i = 0; i < skuArr.length; i++) {
			String skuId = skuArr[i];
			String skuNumStr = skuNumArr[i];
			OrderSku orderSku = orderSkuService.findOrderSku(openId, skuId, "20");
			orderSku.setOrder(mOrder);
			if (orderSku != null) {
				Sku sku = orderSku.getSku();
				if (sku != null && sku.getPrice() >= 0) {
					
					
					int skuNum = Integer.parseInt(skuNumStr);
					
					topayFee += sku.getPrice() * skuNum;
					orderSku.setSkuNum(skuNum);
					orderSku.setType(IN_ORDER);
					logger.info("2.1 新增订单详情记录" + JSON.toJSONString(orderSku));
					orderSkuService.save(orderSku);
					
					orderSkuService.deleteByUserAndSku(openId, skuId);
					logger.info("2.2 清除购物车中的记录:openId=" + openId + ",skuId=" + skuId);
				}
				
			}

		}
		// 3.更新order中的总金额
		mOrder.setRawPrice(topayFee);
		mOrder.setCurrentPrice(topayFee);
		logger.info("3.更新订单的价格为：" + topayFee);
		merOrderService.save(mOrder);

		commonResponse(request,response,openId,mOrder.getId(),"结呗商品",topayFee);
		
	}
	
	
	/**
	 * 未支付的订单，重新购买
	 * 
	 * @param request
	 * @param response
	 * @throws DocumentException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/payByOrder")
	public void payByOrder(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, DocumentException {
		String openId = request.getParameter("openId");
		String orderId = request.getParameter("id");
		MerOrder merOrder = merOrderService.get(orderId);
		if(merOrder != null)commonResponse(request,response,openId,orderId,"结呗商品",merOrder.getCurrentPrice());
		else {
			logger.info("没有找到该订单");
			super.writeFailResponse(response, "", "没有找到该订单,orderId="+orderId+",openId="+openId);
		}
	}
	
	
	
	private void commonResponse(HttpServletRequest request,HttpServletResponse response, String openId,String orderId,
			String orderName,double price) throws UnsupportedEncodingException, DocumentException{
		WeixinMiniProgramApi api = new WeixinMiniProgramApi();
		
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" 
				 + request.getServerPort() + request.getContextPath();
		
		String notifyUrl = basePath + "/api/v1/miniprogram/pay/notify";
		
		super.writeAjaxResponse(response, api.getParm(openId, orderId, orderName, price, notifyUrl));
	}

}
